package com.yh.autobio.modules.adatper;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yh.autobio.AppContext;
import com.yh.autobio.R;
import com.yh.autobio.common.StringUtils;
import com.yh.autobio.modules.bean.TeamChild;
import com.yh.autobio.modules.bean.TeamGroup;
import com.yh.autobio.modules.bean.User;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by kangdong on 2016/4/20.
 */
public class ExpandableAdapter extends BaseExpandableListAdapter {
    Context context;
    ArrayList<TeamGroup> groupDataList;
    private boolean  isShowCheckBox=false;
    HashMap<Integer,Boolean> hashMap;
    String lineName;
    //以选中的子列表项
    private List<String> checkedChildren = new ArrayList<String>();
    private List<TeamChild> checkedTeamChildren = new ArrayList<TeamChild>();
    //父列表项的选中状态：value值为1（选中）、2（部分选中）、3（未选中）
    private Map<String, Integer> groupCheckedStateMap = new HashMap<String, Integer>();
    boolean aBooleanIsClick=true;
    public ExpandableAdapter(Context context, ArrayList<TeamGroup> groupDataList){
        this.context=context;
        this.groupDataList = groupDataList;
        initDate();
    }
    // 初始化isSelected的数据
    private void initDate(){
        //默认设置所有的父列表项和子列表项都为不选中状态
        User user= AppContext.getInstance().getCurrentUser();
        if (user!=null) {
            lineName =user.getDepartmentName()+"-"+user.getGXName();
        }

        int groupCount = getGroupCount();
        for (int groupPosition = 0; groupPosition < groupCount; groupPosition++) {
            try {
                TeamGroup groupItem = groupDataList.get(groupPosition);
                //默认选中当前工序所有人
                String groupName=groupItem.getName();
                if (!StringUtils.isEmpty(lineName) &&!StringUtils.isEmpty(groupName)){
                    if (lineName.equals(groupName)){
                        groupCheckedStateMap.put(groupItem.getGroupid(), 1);
                        List<TeamChild> childrenItems = groupItem.getChildList();
                        if (childrenItems!=null) {
                            for (int j=0;j<childrenItems.size();j++) {
                                TeamChild childrenItem=childrenItems.get(j);
                                checkedTeamChildren.add(childrenItem);
                                checkedChildren.add(childrenItem.getId() + "");
                            }
                        }
                    }else {

                        if (groupItem == null || groupItem.getChildList() == null
                                || groupItem.getChildList().isEmpty()) {
                            groupCheckedStateMap.put(groupItem.getGroupid(), 3);
                            continue;
                        }

                        groupCheckedStateMap.put(groupItem.getGroupid(), 3);
                        List<TeamChild> childrenItems = groupItem.getChildList();
                        for (int j=0;j<childrenItems.size();j++) {
                            TeamChild childrenItem=childrenItems.get(j);
                            checkedChildren.remove(childrenItem.getId() + "");
                        }

                    }
                }else {

                    if (groupItem == null || groupItem.getChildList() == null
                            || groupItem.getChildList().isEmpty()) {
                        groupCheckedStateMap.put(groupItem.getGroupid(), 3);
                        continue;
                    }

                    groupCheckedStateMap.put(groupItem.getGroupid(), 3);
                    List<TeamChild> childrenItems = groupItem.getChildList();
                    for (int j=0;j<childrenItems.size();j++) {
                        TeamChild childrenItem=childrenItems.get(j);
                        checkedChildren.remove(childrenItem.getId() + "");
                    }
                }
            } catch (Exception e) {

            }
        }
    }
    @Override
    public int getGroupCount() {
        if (groupDataList==null) {
            return 0;
        }
        return groupDataList.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        final TeamGroup groupItem = groupDataList.get(groupPosition);
        if (groupItem== null || groupItem.getChildList()==null
                || groupItem.getChildList().isEmpty()) {
            return 0;
        }
        return groupItem.getChildList().size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        if (groupDataList==null) {
            return null;
        }
        return groupDataList.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        final TeamGroup groupItem = groupDataList.get(groupPosition);
        if (groupItem==null || groupItem.getChildList()==null
                || groupItem.getChildList().isEmpty()) {
            return null;
        }
        return groupItem.getChildList().get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return aBooleanIsClick;
    }

    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded,
                             View convertView, ViewGroup parent) {
        TeamGroup groupItem = groupDataList.get(groupPosition);
        String data = this.groupDataList.get(groupPosition).getName();

        GroupViewHolder groupViewHolder = null;
        if(convertView == null)
        {
            convertView = View.inflate(context, R.layout.fragment_list_group, null);
            groupViewHolder = new GroupViewHolder();
            groupViewHolder.tv_name = (TextView) convertView.findViewById(R.id.listTitle);
            groupViewHolder.group_cb_img=(TextView)convertView.findViewById(R.id.group_cb_img);
            groupViewHolder.groupCBLayout=(LinearLayout)convertView.findViewById(R.id.cb_layout);
            convertView.setTag(groupViewHolder);
        }else {
            groupViewHolder = (GroupViewHolder) convertView.getTag();
        }

        groupViewHolder.tv_name.setText(data);
        if(this.isShowCheckBox==true){

            groupViewHolder.group_cb_img.setVisibility(View.VISIBLE);
            groupViewHolder.groupCBLayout.setOnClickListener(new GroupCBLayoutOnClickListener(groupItem));
            int state = groupCheckedStateMap.get(groupItem.getGroupid());
            switch (state) {
                case 1:
                    groupViewHolder.group_cb_img.setBackgroundResource(R.drawable.ck_checked);
                    break;
                case 2:
                    groupViewHolder.group_cb_img.setBackgroundResource(R.drawable.ck_partial_checked);
                    break;
                case 3:
                    groupViewHolder.group_cb_img.setBackgroundResource(R.drawable.ck_unchecked);
                    break;
                default:
                    break;
            }
        }else{
            groupViewHolder.group_cb_img.setVisibility(View.GONE);
        }
        return convertView;
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition,
                             boolean isLastChild, View convertView, ViewGroup parent) {
        final TeamChild childrenItem = (TeamChild) getChild(groupPosition, childPosition);
        Log.d("TAG", "getChildView");
        ViewHolder viewHolder = null;
        if (null == convertView) {
            convertView = View.inflate(context,
                    R.layout.fragment_list_child, null);
            viewHolder = new ViewHolder();
            viewHolder.tv_name = (TextView) convertView
                    .findViewById(R.id.tv_name);
            viewHolder.tv_zhiwei = (TextView) convertView
                    .findViewById(R.id.tv_zhiwei);
            viewHolder.cb = (CheckBox) convertView.findViewById(R.id.check);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.tv_name.setText(groupDataList.get(groupPosition).getChildList().get(childPosition).getName());
        viewHolder.tv_zhiwei.setText(groupDataList.get(groupPosition).getChildList().get(childPosition).getZhiwei());
        if(this.isShowCheckBox==true){
            viewHolder.cb.setVisibility(View.VISIBLE);
            final String userId = childrenItem.getId();
            viewHolder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        if (!checkedChildren.contains(userId)) {
                            checkedChildren.add(userId);
                            checkedTeamChildren.add(childrenItem);
                        }
                    }else {

                        checkedChildren.remove(userId);
                        for (int m=0;m<checkedTeamChildren.size();m++) {
                            TeamChild child=checkedTeamChildren.get(m);
                            String id=child.getId();
                            if (id.equals(userId)) {
                                checkedTeamChildren.remove(m);
                                m=checkedTeamChildren.size();
                            }
                        }
                    }

                    setGroupItemCheckedState(groupDataList.get(groupPosition));
                    ExpandableAdapter.this.notifyDataSetChanged();
                }
            });

            if (checkedChildren.contains(userId)) {
                viewHolder.cb.setChecked(true);
            }else {
                viewHolder.cb.setChecked(false);
            }

        }else{
            viewHolder.cb.setVisibility(View.GONE);
        }
        return convertView;
    }
    public void setShowCheckBox(boolean  isShowCheckBox ){
        this.isShowCheckBox=isShowCheckBox;
    }
    private void setGroupItemCheckedState(TeamGroup groupItem){
        List<TeamChild> childrenItems = groupItem.getChildList();
        if (childrenItems==null || childrenItems.isEmpty()) {
            groupCheckedStateMap.put(groupItem.getGroupid(), 3);
            return;
        }

        int  checkedCount = 0;
        for (TeamChild childrenItem : childrenItems) {
            if (checkedChildren.contains(childrenItem.getId())) {
                checkedCount ++;
            }
        }
        int state = 3;
        if (checkedCount==0) {
            state = 3;
        }else if (checkedCount==childrenItems.size()) {
            state = 1;
        }else {
            state = 2;
        }

        groupCheckedStateMap.put(groupItem.getGroupid(), state);
    }

    public  class ViewHolder {
        TextView tv_name;
        TextView tv_zhiwei;
        public CheckBox cb;
    }

    public  class GroupViewHolder {
        TextView tv_name;
        public TextView group_cb_img;
        LinearLayout groupCBLayout;
    }
    public class GroupCBLayoutOnClickListener implements View.OnClickListener {

        private TeamGroup groupItem;

        public GroupCBLayoutOnClickListener(TeamGroup groupItem){
            this.groupItem = groupItem;
        }

        @Override
        public void onClick(View v) {
            List<TeamChild> childrenItems = groupItem.getChildList();
            if (childrenItems==null || childrenItems.isEmpty()) {
                groupCheckedStateMap.put(groupItem.getGroupid(), 3);
                return;
            }
            int  checkedCount = 0;
            for (TeamChild childrenItem : childrenItems) {
                if (checkedChildren.contains(childrenItem.getId())) {
                    checkedCount ++;
                }
            }

            boolean checked = false;
            if (checkedCount==childrenItems.size()) {
                checked = false;
                groupCheckedStateMap.put(groupItem.getGroupid(), 3);
            }else{
                checked = true;
                groupCheckedStateMap.put(groupItem.getGroupid(), 1);
            }
            for (int j=0;j<childrenItems.size();j++) {
                TeamChild childrenItem=childrenItems.get(j);
                String holderKey = childrenItem.getId()+ "";
                if (checked) {
                    if (!checkedChildren.contains(holderKey)) {
                        checkedChildren.add(holderKey);
                        checkedTeamChildren.add(childrenItem);
                    }
                }else {
                    checkedChildren.remove(holderKey);
                    if (j<checkedTeamChildren.size()) {
                        checkedTeamChildren.remove(j);
                    }
                }
            }

            ExpandableAdapter.this.notifyDataSetChanged();
        }
    }

    public List<TeamChild> getCheckedTeamChildren() {
        return checkedTeamChildren;
    }

    public void setCheckedTeamChildren(List<TeamChild> checkedTeamChildren) {
        this.checkedTeamChildren = checkedTeamChildren;
    }

    public List<String> getCheckedRecords() {
        return checkedChildren;
    }


    public List<String> getCheckedChildren() {
        return checkedChildren;
    }
    public boolean setIsClick(boolean aBooleanIsClick ){
         this.aBooleanIsClick=aBooleanIsClick;
        return this.aBooleanIsClick;
    }
}
